package com.zzj.ecology.admin.controller.system;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.zzj.ecology.system.dto.HttpResult;
import com.zzj.ecology.system.dto.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码
 */
@Controller
@RequestMapping(value = "/captcha")
public class SysCaptchaController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    private static final String KAPTCHA_MATH = "math";
    private static final String KAPTCHA_CHAR = "char";

    /**
     * 验证码生成
     */
    @GetMapping(value = "/image")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream out = null;
        try {
            HttpSession session = request.getSession();
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");

            String type = request.getParameter("type");
//            String capStr = null;
//            String code = null;
//            BufferedImage bi = null;
//            if ("math".equals(type)) {
//                String capText = captchaProducerMath.createText();
//                capStr = capText.substring(0, capText.lastIndexOf("@"));
//                code = capText.substring(capText.lastIndexOf("@") + 1);
//                bi = captchaProducerMath.createImage(capStr);
//            } else if ("char".equals(type)) {
//                capStr = code = captchaProducer.createText();
//                bi = captchaProducer.createImage(capStr);
//            }

            Map<String, Object> kaptchaInfo = getKaptchaInfo(type);
            String code = (String) kaptchaInfo.get("code");
            BufferedImage bi = (BufferedImage) kaptchaInfo.get("image");

            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/base64Image")
    public R getBase64KaptchaImage(String type, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> kaptchaInfo = getKaptchaInfo(type);
        String code = (String) kaptchaInfo.get("code");
        BufferedImage image = (BufferedImage) kaptchaInfo.get("image");

        req.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, code);//session
        ByteArrayOutputStream bos = new ByteArrayOutputStream();// 把生成的照片写到此流中
        ImageIO.write(image, "png", bos);// 将绘制得图片输出到流
        String imgStr = com.alibaba.druid.util.Base64.byteArrayToBase64(bos.toByteArray());// 使用 com.alibaba.druid.util.Base64 方法
        return R.ok().data(R.CAPTCHA, imgStr);//把 image BASE64格式 返回前端
    }

    private Map<String, Object> getKaptchaInfo(String type) {
        Map<String, Object> data = new HashMap<>();
        String capStr = null;//
        String code = null;//验证码信息
        BufferedImage bi = null;//验证码图片
        if (KAPTCHA_MATH.equals(type)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            bi = captchaProducerMath.createImage(capStr);
        } else if (KAPTCHA_CHAR.equals(type)) {
            capStr = code = captchaProducer.createText();
            bi = captchaProducer.createImage(capStr);
        }
        data.put("code", code);
        data.put("image", bi);
        return data;
    }


//    /**
//     * 获取到验证码
//     * @param resp
//     * @param session
//     */
//    @GetMapping(value= {"/user/verifycode1"})
//    public void verifycode(HttpServletResponse resp, HttpSession session) {
//        try {
//            VerifyCode verifyCode = new VerifyCode();
//            BufferedImage image = verifyCode.getImage();
//            VerifyCode.output(image, resp.getOutputStream());//把图片写到指定流中
//            session.setAttribute("key", verifyCode.getText());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 使用Google的 DefaultKaptcha 生成 kaptcha
//     * @param req
//     * @param resp
//     * @return
//     */
//    @GetMapping(value = "/admin/sysUser/ajax/randomCode")
//    public HttpResult getBase64Kaptcha(HttpServletRequest req, HttpServletResponse resp) {
//        try {
//            DefaultKaptcha captchaProducer = new DefaultKaptcha();
//            Properties properties = new Properties();
//            properties.setProperty("kaptcha.border", "yes");
//            properties.setProperty("kaptcha.border.color", "105,179,90");
//            properties.setProperty("kaptcha.textproducer.font.color", "red");
//            properties.setProperty("kaptcha.image.width", "125");
//            properties.setProperty("kaptcha.image.height", "45");
//            properties.setProperty("kaptcha.textproducer.font.size", "45");
//            properties.setProperty("kaptcha.session.key", "verifyCode");//与页面上的name一致
//            properties.setProperty("kaptcha.textproducer.char.length", "4");
//            properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
//            Config config = new Config(properties);
//            captchaProducer.setConfig(config);
//            //return  captchaProducer;
//
//            // 获取验证码上的文字
//            String capText = captchaProducer.createText();
//            req.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);//session
//
//            //  将文件渲染到图片上
//            BufferedImage image = captchaProducer.createImage(capText);
//
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();// 把生成的照片写到此流中
//            ImageIO.write(image, "png", bos);// 将绘制得图片输出到流
//            String imgStr = com.alibaba.druid.util.Base64.byteArrayToBase64(bos.toByteArray());// 使用 com.alibaba.druid.util.Base64 方法
//            return HttpResult.success().add(Constant.RESP_DATA_KEY, imgStr);//把 image BASE64格式 返回前端
//        } catch (IOException e) {
//            return HttpResult.error();
//        }
//    }
//
//    /**
//     * 获取 BASE64 照片格式  验证码
//     * @param resp
//     * @param session
//     * @return
//     */
//    @GetMapping(value = "/admin/sysUser/ajax/verifyCode")
//    public HttpResult getBase64VerifyCode(HttpServletResponse resp, HttpSession session) {
//        String imgStr = null;
//        Base64.Encoder encoder = Base64.getEncoder();
//        //imgStr = encoder.encodeToString(src);
//        try {
//            VerifyCode verifyCode = new VerifyCode();
//            BufferedImage image = verifyCode.getImage();//得到照片
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();// 把生成的照片写到此流中
//            ImageIO.write(image, "png", bos);// 将绘制得图片输出到流
//            //imgStr = Base64Utils.encodeToUrlSafeString(bos.toByteArray());//前端AJAX时加载到时, 无法展示
//            imgStr = Base64Utils.encodeToString(bos.toByteArray());//前端AJAX时加载到时可以展示
//            session.setAttribute("verifyCode", verifyCode.getText());// 验证码信息
//            //String imgStr1 = com.alibaba.druid.util.Base64.byteArrayToBase64(bos.toByteArray());// 使用 com.alibaba.druid.util.Base64 方法
//            return HttpResult.success().add(Constant.RESP_DATA_KEY, imgStr);//把 image BASE64格式 返回前端
//        } catch (IOException e) {
//            return HttpResult.error();
//        }
//        // <img src="data:image/jpg;base64,${String}" class="images" border="5px"/>
//    }

}
